import java.util.*;

public class LinkedListPartitioning {
    public static void main(String[] args) {
        // 创建测试链表: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1
        ListNode head = new ListNode(3);
        head.next = new ListNode(5);
        head.next.next = new ListNode(8);
        head.next.next.next = new ListNode(5);
        head.next.next.next.next = new ListNode(10);
        head.next.next.next.next.next = new ListNode(2);
        head.next.next.next.next.next.next = new ListNode(1);

        int x = 5; // 分割值

        System.out.println("原始链表:");
        printList(head);

        ListNode partitionedHead = Partition.partition(head, x);

        System.out.println("\n分割后的链表 (值 < " + x + " 在前面):");
        printList(partitionedHead);
    }

    private static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
    public static class Partition {
        public static ListNode partition(ListNode pHead, int val) {
            if(pHead == null) {
                return null;
            }

            //栈（后进先出）
            Stack<Integer> stack = new Stack<>();

            //遍历指针
            ListNode cur = pHead;
            //重构指针
            ListNode prev = null;

            while(cur!=null) {
                if(cur.val < val) {
                    //白进栈
                    stack.add(cur.val);
                    //开头所有白才满足
                    if(cur == pHead) {
                        //主指针和遍历指针向后，最终主指针停在黑1
                        pHead = pHead.next;
                        cur = pHead;
                    }else {
                        cur = cur.next;
                        //跳过孤儿白
                        prev.next = cur;
                    }
                }else {
                    //prev遍历黑
                    prev = cur;
                    cur = cur.next;
                }
            }

            while(!stack.isEmpty()) {
                //栈吐
                ListNode newNode = new ListNode(stack.pop());
                //连接全白与黑1
                newNode.next = pHead;
                pHead = newNode;
            }

            return pHead;
        }
    }
}

